<template>
  <div class="container">
    <!-- 注销按钮 -->
    <!-- <div class="logout-container">
      <el-button type="primary" @click="logout">注销</el-button>
    </div> -->
    
    <!-- 左侧列表区域 -->
    <!-- <div class="list" :class="{ 'list-collapsed': isCollapsed }">
      <div class="database-container">
        <el-button
          type="primary"
          class="add-database-btn"
          @click="addDatabaseDialogVisible = true"
        >
          <el-icon><Plus /></el-icon>
          <span>新增数据库</span>
        </el-button>
        <div class="database-list">
          <template v-for="item in databases" :key="item.id">
            <div
              class="database-item"
              :class="{ highlight: selectedDatabaseId === item.id }"
              @click="selectDatabase(item.id)"
            >
              <div class="database-content">
                <el-tooltip :content="item.name">
                  <span class="database-name">{{ item.name }}</span>
                </el-tooltip>
                
                <el-dropdown trigger="hover" @click.stop>
                  <el-button
                    type="primary"
                    size="small"
                    class="action-btn"
                    text
                  >
                    <el-icon><Setting /></el-icon>
                    操作
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="showAddColumnDialog(item.id)">
                        <el-icon><Plus /></el-icon>添加列
                      </el-dropdown-item>
                      <el-dropdown-item @click="showDeleteColumnDialog(item.id)">
                        <el-icon><Minus /></el-icon>删除列
                      </el-dropdown-item>
                      <el-dropdown-item divided @click="delDatabase(item.id)">
                        <el-icon color="#ff4949"><Delete /></el-icon>
                        <span style="color: #ff4949">删除数据库</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </template>
        </div>
      </div>
            <div class="list-trigger" @click="toggleCollapse">
        <el-icon class="trigger-icon">
          <component :is="isCollapsed ? 'ArrowRight' : 'ArrowLeft'" />
        </el-icon>
      </div>
    </div> -->
    
    <!-- 右侧内容区域 -->
    <div class="data" :class="{ 'data-expanded': isCollapsed }">
      <div class="data-action">
        <el-button-group>
          <el-button type="primary" class="add-database-btn" @click="addDatabaseDialogVisible = true">
            <el-icon><Plus /></el-icon>
            <span>新增数据库</span>
          </el-button>
          <el-button type="primary" @click="manageDatabaseDialogVisible = true" :icon="MoreFilled">
            管理数据库
          </el-button>
        </el-button-group>

        <el-button-group>
          <el-button type="primary" @click="addDataDialogVisble = true">
            <el-icon><Plus /></el-icon>
            <span>新增数据</span>
          </el-button>
          <el-button type="danger" @click="batchDelData" :disabled="!selectedRows.length" :icon="Delete">
            批量删除
          </el-button>
          <el-button @click="batchEditDialogVisble = true" :disabled="!selectedRows.length" :icon="Edit">
            批量编辑
          </el-button>
        </el-button-group>

        <el-button-group>
          
          <el-upload
            class="upload-demo"
            ref="upload"
            action="http://127.0.0.1:8000/api/upload"
            :on-success="handleSuccess"
            :file-list="fileList"
            :headers="httpHeader"   
            :auto-upload="false"
            >
            <template #trigger>
      <el-button type="primary">批量导入</el-button>
    </template>
    <el-button class="ml-3" type="success" @click="submitUpload">
      上传到服务器
    </el-button>
              <!-- <el-button slot="trigger" size="small" type="primary">批量导入</el-button> -->
              <!-- <div style="display: inline;">
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
              </div> -->
            </el-upload>
        </el-button-group>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="selectRow"
        border
        :max-height="tableHeight"
        fit
      >
        <el-table-column
          type="selection"
          width="55"
          fixed="left"
        />
        
        <template v-for="column in columns" :key="column.id">
          <el-table-column
            :prop="column.id"
            :label="column.name"
            min-width="120"
            show-overflow-tooltip
            resizable
          />
        </template>

        <el-table-column
          label="ID"
          prop="id"
          width="180"
          resizable
          show-overflow-tooltip
        />

        <el-table-column
          label="更新时间"
          prop="updated_at"
          width="180"
          resizable
        >
          <template #default="scope">
            {{ formatDateTime(scope.row.updated_at) }}
          </template>
        </el-table-column>

        <el-table-column
          label="读取状态"
          prop="read_status"
          width="100"
          fixed="right"
        >
          <template #default="scope">
            <el-tag
              :type="scope.row.read_status ? 'success' : 'info'"
              @click="toggleReadStatus(scope.row, scope.$index)"
              class="status-tag"
            >
              {{ scope.row.read_status ? '已读' : '未读' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="操作"
          width="150"
          fixed="right"
        >
          <template #default="scope">
            <el-button type="primary" link @click="editData(scope)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" link @click="delData(scope.$index)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="totalItems"
          :background="true"
          layout="total, prev, pager, next"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <el-dialog
    v-model="manageDatabaseDialogVisible"
    title="管理数据库"
    width="30%"
  >
  <div class="database-list" >
          <template style="height:500px" v-for="item in databases" :key="item.id">
            <div
              class="database-item"
              :class="{ highlight: Number(id) === item.id }"
            >
              <div class="database-content">
                <el-tooltip :content="item.name">
                  <span class="database-name">{{ item.name }}</span>
                </el-tooltip>
                <el-dropdown trigger="hover" @click.stop>
                  <el-button
                    type="primary"
                    size="large"
                    class="action-btn"
                    text
                  >
                    <el-icon><Setting /></el-icon>
                    <span class="action-text">操作</span>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="showAddColumnDialog(item.id)">
                        <el-icon><Plus /></el-icon>添加列
                      </el-dropdown-item>
                      <el-dropdown-item @click="showDeleteColumnDialog(item.id)">
                        <el-icon><Minus /></el-icon>删除列
                      </el-dropdown-item>
                      <el-dropdown-item divided @click="delDatabase(item.id)">
                        <el-icon color="#ff4949"><Delete /></el-icon>
                        <span style="color: #ff4949">删除数据库</span>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </template>
        </div>
  </el-dialog>


  <el-dialog
    v-model="addDatabaseDialogVisible"
    title="新增数据库"
    width="500"
    @close="resetDataBaseForm"
  >
    <el-form 
      :model="dataBaseForm" 
      ref="dataBaseFormRef"
      :rules="formRules"
    >
      <el-form-item
        prop="name"
        label="数据库名称"
      >
        <el-input v-model="dataBaseForm.name" autocomplete="off" />
      </el-form-item>
      
      <el-form-item
        v-for="(domain, index) in dataBaseForm.domains"
        :key="domain.key"
        :label="'列' + (index + 1)"
        :prop="'domains.' + index + '.value'"
      >
        <el-input v-model="domain.value" />
        <el-button
          @click.prevent="removeDomain(domain)"
          type="danger"
          link
          size="small"
        >
          删除列
        </el-button>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="addDomain" plain>
          新增列
        </el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDatabaseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDataBaseForm">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="addDataDialogVisble"
    title="新增数据"
    width="500"
    @close="resetDataForm"
  >
    <el-form :model="dataForm" ref="dataFormRef">
      <template v-for="(item, index) in columns" :key="index">
        <el-form-item
          :label="item.name"
          :prop="item.id"
        >
          <el-input v-model="dataForm[item.id]" autocomplete="off" />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDataDialogVisble = false">取消</el-button>
        <el-button type="primary" @click="submitDataForm">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="editDataDialogVisble"
    title="编辑数据"
    width="500"
    @close="resetDataForm"
  >
    <el-form :model="dataForm" ref="dataFormRef">
      <template v-for="(item, index) in columns" :key="index">
        <el-form-item
          :label="item.name"
          :prop="item.id"
          :rules="{
            required: true,
            message: '不能为空',
            trigger: 'blur',
          }"
        >
          <el-input v-model="dataForm[item.id]" autocomplete="off" />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editDataDialogVisble = false">取消</el-button>
        <el-button type="primary" @click="submitEditDataForm">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="batchEditDialogVisble"
    title="批量编辑数据"
    width="500"
    @close="resetDataForm"
  >
    <el-form :model="dataForm" ref="dataFormRef">
      <template v-for="(item, index) in columns" :key="index">
        <el-form-item :label="item.name" :prop="item.id">
          
          <el-input v-model="dataForm[item.id]" autocomplete="off" />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="batchEditDialogVisble = false">取消</el-button>
        <el-button type="primary" @click="submitBatchEditDataForm">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="searchDialogVisible"
    title="查询数据"
    width="500"
  >
    <el-form :model="searchForm" ref="searchFormRef">
      <el-form-item label="选择列">
        <el-select v-model="searchForm.columnId" placeholder="请选择列">
          <el-option
            v-for="column in columns"
            :key="column.id"
            :label="column.name"
            :value="column.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="搜索内容">
        <el-input v-model="searchForm.value" placeholder="请输入搜索内容" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="searchDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSearch">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="addColumnDialogVisible"
    title="添加新列"
    width="500"
    @close="resetAddColumnForm"
  >
    <el-form :model="columnForm" ref="columnFormRef" :rules="columnFormRules">
      <el-form-item
        label="列名"
        prop="name"
      >
        <el-input v-model="columnForm.name" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addColumnDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddColumn">确定</el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="deleteColumnDialogVisible"
    title="删除列"
    width="500"
  >
    <el-form>
      <el-form-item label="选择要删除的列">
        <el-select v-model="selectedColumnId" placeholder="请选择列">
          <el-option
            v-for="column in columns"
            :key="column.id"
            :label="column.name"
            :value="column.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="deleteColumnDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="submitDeleteColumn">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, watch, reactive, onMounted } from "vue";
import { ElMessage,ElMessageBox } from "element-plus";
import req from "@/req";
import { v4 as uuidv4 } from "uuid";
import type { FormRules, FormItemRule } from 'element-plus'
import { More, Plus, Minus, Delete, Setting, ArrowLeft, ArrowRight, Expand, Fold, Edit, Search, MuteNotification, MoreFilled, UploadFilled, Download } from '@element-plus/icons-vue'

interface DomainItem {
  key: number;
  value: string;
}

interface Column {
  id: string;
  name: string;
  type?: string;
}

interface Database {
  id: number;
  name: string;
  columns?: Column[];
}

interface TableData {
  id: string | number;
  updated_at: number;
  read_status: boolean;
  [key: string]: any;
}

interface ApiResponse<T = any> {
  success: boolean;
  data: T;
  message?: string;
}

interface DataForm {
  [key: string]: any;
  create_time?: number;
  read_status?: boolean;
}

interface DataBaseForm {
  name: string;
  domains: { key: number; value: string }[];
}

interface ParsedData {
  username: string;
  password: string;
}

// 添加响应类型接口
interface BatchAddResponse {
  success: boolean;
  message?: string;
  data?: any;
}

const databases = ref<Database[]>([]);
const columns = ref<Column[]>([]);
const tableData = ref<TableData[]>([]);
const selectedDatabaseId = ref<number | null>(null);
const selectedRows = ref<{ index: number; row: TableData }[]>([]);
const manageDatabaseDialogVisible = ref(false);
const importDataDialogVisible = ref(false);
const totalItems = ref(0);
const pageSize = ref(20);
const currentPage = ref(1);
const parsedData = ref<ParsedData[]>([]);
const loading = ref(false);
const fileList = ref([]);
import type { UploadInstance } from 'element-plus'

const upload = ref<UploadInstance>()
const httpHeader = ref({
          'Authorization': ''
      });


const submitUpload = () => {
    httpHeader.value.Authorization = `Bearer ${localStorage.getItem("token")}`,
    upload.value.submit()
    }


const handleSuccess = (response: any) => {
          console.log(response, "response");
          if(response.data.code == 200){
            fileList.value = []
            console.log(response);
            ElMessage.success(response.message);
          } else {
            ElMessage.error(response.message);
          }
            // this.handleFilter()
        }

const formRules: FormRules = {
  name: [
    { required: true, message: '数据库名称不能为空', trigger: 'blur' },
    { min: 1, message: '长度不能为0', trigger: 'blur' }
  ],
  domains: [{
    required: true,
    message: '请至少添加一列',
    trigger: 'change',
    validator: (rule: any, value: any, callback: any) => {
      if (value.length === 0) {
        callback(new Error('请至少添加一列'));
      } else {
        const emptyColumns = value.filter((domain: any) => !domain.value.trim());
        if (emptyColumns.length > 0) {
          callback(new Error('列名不能为空'));
        } else {
          callback();
        }
      }
    }
  }]
};





const getDatabases = async () => {
  const res = await req({
    url: "/database",
  }) as ApiResponse<Database[]>;
  
  console.log(res.data);
  databases.value = res.data;
  await getDataBaseInfo(Number(id.value), currentPage.value, pageSize.value);
};


getDatabases();
const getDataBaseInfo = async (id: number, page: number, size: number) => {
  loading.value = true;
  try {
    console.log('请求参数:', { id, page, size });
    
    const res = await req({
      url: `/database/${id}`,
      method: 'get',
      params: { 
        page, 
        page_size: size 
      },
    }) as ApiResponse;
    
    console.log('API返回数据:', res);
    
    if (res.success && res.data) {
      columns.value = res.data.columns || [];
      console.log('设置列信息:', columns.value);
      
      if (Array.isArray(res.data.data)) {
        tableData.value = res.data.data.map((item: any) => ({
          ...item,
          id: item.id || '',
          updated_at: item.updated_at || Date.now(),
          read_status: typeof item.read_status === 'boolean' ? item.read_status : false
        }));
      } else {
        tableData.value = [];
      }
      console.log('设置表格数据:', tableData.value);
      
      totalItems.value = res.data.total || 0;
      console.log('设置总数:', totalItems.value);
    } else {
      ElMessage.error(res.message || '获取数据失败');
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取数据失败，请重试');
  } finally {
    loading.value = false;
  }
};

// watch(
//   () => databases.value,
//   (newDatabases) => {
//     if (newDatabases.length > 0) {
//       selectedDatabaseId.value = newDatabases[0].id;
//     } else {
//       selectedDatabaseId.value = null;
//     }
//   },
//   { immediate: true }
// );
import { useRoute } from 'vue-router';
const route = useRoute();
const id = ref(route.params.id); 
watch(
  () => route.params.id,
  async (newId) => {
    if (!newId) return;
    id.value = newId;
    await getDataBaseInfo(Number(newId), currentPage.value, pageSize.value);
  },
  { immediate: true }
);



const handleCurrentChange = (page: number) => {
  currentPage.value = page;
  if (selectedDatabaseId.value !== null) {
    getDataBaseInfo(selectedDatabaseId.value, currentPage.value, pageSize.value);
  }
};

const addDatabaseDialogVisible = ref(false);
const dataBaseForm = reactive<DataBaseForm>({
  name: '',
  domains: []
});

const resetDataBaseForm = () => {
  dataBaseForm.name = '';
  dataBaseForm.domains = [];
};

const dataBaseFormRef = ref(null);
const removeDomain = (item: { key: number; value: string }) => {
  const index = dataBaseForm.domains.indexOf(item);
  if (index !== -1) {
    dataBaseForm.domains.splice(index, 1);
  }
};

const addDomain = () => {
  dataBaseForm.domains.push({
    key: Date.now(),
    value: ''
  });
};

const submitDataBaseForm = async () => {
  if (!dataBaseFormRef.value) return;
  
  try {
    if (!dataBaseForm.name.trim()) {
      ElMessage.error('数据库名称不能为空');
      return;
    }

    if (dataBaseForm.domains.length === 0) {
      ElMessage.error('请至少添加一列');
      return;
    }

    const emptyColumns = dataBaseForm.domains.filter(domain => !domain.value.trim());
    if (emptyColumns.length > 0) {
      ElMessage.error('列名不能为空');
      return;
    }

    const payload = {
      name: dataBaseForm.name.trim(),
      columns: dataBaseForm.domains.map((item) => ({
        name: item.value.trim(),
        id: uuidv4()
      })),
    };

    const res = await req({
      url: "/database",
      method: "post",
      data: payload,
    }) as ApiResponse;
    
    if (res.success) {
      await getDatabases();
      ElMessage.success("数据库新增成功");
      addDatabaseDialogVisible.value = false;
      resetDataBaseForm();
    } else {
      ElMessage.error(res.message || "创建失败");
    }
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败，请重试');
  }
};

const delDatabase = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该数据库吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const res = await req({
      url: `/database/${id}`,
      method: "delete",
    }) as ApiResponse;
    if (res.success) {
      await getDatabases();
      ElMessage.success("删除成功");
    }
  } catch (error) {
    ElMessage.info("已取消删除")
  }
};

const addDataDialogVisble = ref(false);
const dataForm = reactive<DataForm>({});
const dataFormRef = ref(null);
const resetDataForm = () => {
  console.log(dataForm, "GGG");
  for (let key in dataForm) {
    if (dataForm.hasOwnProperty(key)) {
      delete dataForm[key];
    }
  }
  console.log(dataForm, "clear ");
};
const submitDataForm = async () => {
  try {
    const formData = {
      ...dataForm,
      read_status: false,
      updated_at: Date.now(),
    };
    
    const res = await req({
      url: "/data",
      method: "post",
      data: {
        data: formData,
        id: id.value,
        action: 1,
        index: 0,
      },
    }) as ApiResponse;
    
    if (res.success) {
      await getDataBaseInfo(Number(id.value), currentPage.value, pageSize.value);
      ElMessage.success("添加成功");
      addDataDialogVisble.value = false;
      resetDataForm();
    } else {
      ElMessage.error(res.message || "添加失败");
    }
  } catch (error) {
    console.error('添加数据失败:', error);
    ElMessage.error('添加失败，请重试');
  }
};

const delData = async (index: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该数据吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const res = await req({
      url: "/data",
      method: "post",
      data: {
        data: dataForm,
        id: id.value,
        action: 2,
        index: index,
      },
    }) as ApiResponse;
    if (res.success) {
      await getDataBaseInfo(Number(id.value), currentPage.value, pageSize.value);
      ElMessage.success("删除成功");
    }
  } catch (error) {
    ElMessage.info("已取消删除")
  }
};

const editDataDialogVisble = ref(false);
const editDataId = ref(0);

const editData = (scope: { row: TableData; $index: number }) => {
  editDataDialogVisble.value = true;
  Object.assign(dataForm, scope.row);
  editDataId.value = scope.$index;
};

const handleFileChange = () => {

  
}
const handleFileRemove = () => {

  
}

const handleImportData = () => {
}


const submitEditDataForm = async () => {
  dataFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const formData = {
        ...dataForm,
        updated_at: Date.now(),
        read_status: typeof dataForm.read_status === 'boolean' ? dataForm.read_status : false
      };

      const res = await req({
        url: "/data",
        method: "post",
        data: {
          data: formData,
          id: id.value,
          action: 3,
          index: editDataId.value,
        },
      }) as ApiResponse;
      
      if (res.success) {
        await getDataBaseInfo(Number(id.value), currentPage.value, pageSize.value);
        ElMessage.success("编辑成功");
        editDataDialogVisble.value = false;
      }
    }
  });
};

const selectRow = (selection: TableData[]) => {
  selectedRows.value = selection.map((selectedRow) => {
    const index = tableData.value.findIndex((row) => row === selectedRow);
    return { index, row: selectedRow };
  });
};

const batchDelData = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的${selectedRows.value.length}条数据吗？`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    const res = await req({
      url: "/batch_data",
      method: "post",
      data: {
        data: dataForm,
        action: 2,
        id: id.value,
        indexs: selectedRows.value.map((selectedRow) => selectedRow.index),
      },
    }) as ApiResponse;
    if (res.success) {
      await getDataBaseInfo(Number(id.value), currentPage.value, pageSize.value);
      ElMessage.success("批量删除成功");
    }
  } catch (error) {
    ElMessage.info("已取消删除")
  }
};

const batchEditDialogVisble = ref(false);

const submitBatchEditDataForm = async () => {
  dataFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const formData = {
        ...dataForm,
        updated_at: Date.now(),
        read_status: false
      };
      
      const res = await req({
        url: "/batch_data",
        method: "post",
        data: {
          data: formData,
          action: 3,
          id: id.value,
          indexs: selectedRows.value.map((selectedRow) => selectedRow.index),
        },
      }) as ApiResponse;
      
      if (res.success) {
        await getDataBaseInfo(Number(id.value), currentPage.value, pageSize.value);
        ElMessage.success("批量编辑成功");
        batchEditDialogVisble.value = false;
      }
    }
  });
};

const formatDateTime = (timestamp: number) => {
  if (!timestamp) return '-';
  const date = new Date(timestamp);
  return date.toLocaleString();
};

const toggleReadStatus = async (row: TableData, index: number) => {
  try {
    const newStatus = !row.read_status;
    const formData = {
      ...row,
      read_status: newStatus
    };
    
    const res = await req({
      url: "/data",
      method: "post",
      data: {
        data: formData,
        id: id.value,
        action: 3,
        index: index,
      },
    }) as ApiResponse;
    
    if (res.success) {
      row.read_status = newStatus;
      ElMessage.success(newStatus ? "已标记为已读" : "已标记为未读");
      
      await getDataBaseInfo(Number(id.value), currentPage.value, pageSize.value);
    }
  } catch (error) {
    ElMessage.error("状态更新失败");
  }
};

const searchDialogVisible = ref(false);
const searchForm = reactive({
  columnId: '',
  value: ''
});

const submitSearch = async () => {
  if (!searchForm.columnId || !searchForm.value.trim()) {
    ElMessage.error('请选择列并输入搜索内容');
    return;
  }

  try {
    const selectedColumn = columns.value.find(col => col.id === searchForm.columnId);
    if (!selectedColumn) {
      ElMessage.error('列不存在');
      return;
    }

    const res = await req({
      url: '/query',
      method: 'get',
      params: {
        database_name: databases.value.find(db => db.id === Number(id.value))?.name,
        column_name: `${selectedColumn.name}:${searchForm.value.trim()}`
      }
    }) as ApiResponse;

    if (res.success) {
      tableData.value = res.data;
      searchDialogVisible.value = false;
      ElMessage.success('查询成功');
    } else {
      ElMessage.error(res.message || '查询失败');
    }
  } catch (error) {
    console.error('查询失败:', error);
    ElMessage.error('查询失败，请重试');
  }
};

const addColumnDialogVisible = ref(false);
const currentDatabaseId = ref<number | null>(null);
const columnForm = reactive({
  name: '',
});
const columnFormRef = ref(null);

const columnFormRules = {
  name: [
    { required: true, message: '列名不能为空', trigger: 'blur' },
    { min: 1, message: '长度不能为0', trigger: 'blur' }
  ]
};

const showAddColumnDialog = (databaseId: number) => {
  currentDatabaseId.value = databaseId;
  addColumnDialogVisible.value = true;
};

const resetAddColumnForm = () => {
  columnForm.name = '';
};

const submitAddColumn = async () => {
  if (!columnFormRef.value) return;
  
  try {
    if (!columnForm.name.trim()) {
      ElMessage.error('列名不能为空');
      return;
    }

    const payload = {
      database_id: currentDatabaseId.value,
      column_name: columnForm.name.trim(),
      column_type: 'text'
    };

    const res = await req({
      url: "/database/add_column",
      method: "post",
      data: payload,
    }) as ApiResponse;
    
    if (res.success) {
      if (id.value) {
        await getDataBaseInfo(Number(id.value), currentPage.value, pageSize.value);
      }
      ElMessage.success("添加列成功");
      addColumnDialogVisible.value = false;
      resetAddColumnForm();
    } else {
      ElMessage.error(res.message || "添加失败");
    }
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败，请重试');
  }
};

const deleteColumnDialogVisible = ref(false);
const selectedColumnId = ref('');

const showDeleteColumnDialog = (databaseId: number) => {
  currentDatabaseId.value = databaseId;
  deleteColumnDialogVisible.value = true;
};

const submitDeleteColumn = async () => {
  if (!selectedColumnId.value) {
    ElMessage.error('请选择要删除的列');
    return;
  }

  try {
    const res = await req({
      url: "/database/delete_column",
      method: "post",
      data: {
        database_id: currentDatabaseId.value,
        column_id: selectedColumnId.value
      },
    }) as ApiResponse;
    
    if (res.success) {
      if (id.value) {
        await getDataBaseInfo(Number(id.value), currentPage.value, pageSize.value);
      }
      ElMessage.success("删除列成功");
      deleteColumnDialogVisible.value = false;
      selectedColumnId.value = '';
    } else {
      ElMessage.error(res.message || "删除失败");
    }
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败，请重试');
  }
};

const tableHeight = ref(500);

onMounted(() => {
  calculateTableHeight();
  window.addEventListener('resize', calculateTableHeight);
});

const calculateTableHeight = () => {
  const windowHeight = window.innerHeight;
  tableHeight.value = windowHeight - 200;
};

// 控制列表收缩状态
const isCollapsed = ref(false)

// 切换收缩状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

// 添加注销方法
const logout = () => {
  localStorage.removeItem('token')
  window.location.href = '/login'
}


</script>

<style scoped>
.container {
  display: flex;
  height: 100%;
  width: 100%;
  position: relative;
}

.logout-container {
  position: fixed;
  top: 16px;
  right: 16px;
  z-index: 1000;
}

.list {
  width: 250px;
  background: #fff;
  border-right: 1px solid #e6e6e6;
  transition: all 0.3s ease;
  position: relative;
  height: 100%;
  flex-shrink: 0;
  overflow: hidden;
}

.list-collapsed {
  width: 0;
}

.database-container {
  width: 250px;
  box-sizing: border-box;
  padding: 16px;
  transition: all 0.3s ease;
}

.database-list {
  width: 100%;
}

.database-item {
  font-size: 30px;
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s;
}

.database-item:hover {
  background-color: #f5f7fa;
}

.database-content {
  display: flex;
  align-items: center;
  width: 100%;
  gap: 8px;
}

.database-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  min-width: 0;
  font-size: 14px;
}

.action-btn {
  flex-shrink: 0;
  padding: 8px 16px;
  margin-left: auto;
  font-size: 20px;
}

.action-btn .el-icon {
  font-size: 20px;
  margin-right: 4px;
}

.add-database-btn {
  margin: 0 16px 16px 0;
}

.highlight {
  background-color: #ecf5ff;
}

.data {
  flex: 1;
  padding: 20px;
  background-color: #fff;
  transition: margin-left 0.3s ease;
  overflow: auto;
  min-width: 0;
}

.data-action {
  margin-bottom: 16px;
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

:deep(.el-dropdown-menu__item) {
  font-size: 18px;
  padding: 12px 20px;
}

:deep(.el-dropdown-menu__item .el-icon) {
  font-size: 18px;
  margin-right: 8px;
}

.import-container {
  padding: 20px;
}

.preview-container {
  margin-top: 20px;
}

.preview-container h3 {
  margin-bottom: 10px;
  color: #606266;
}

.total-count {
  margin-top: 10px;
  text-align: right;
  color: #909399;
}

.dialog-footer {
  margin-top: 20px;
}

:deep(.el-upload-dragger) {
  width: 100%;
}

:deep(.el-upload) {
  width: 100%;
}
</style>
